package  
{
	import net.flashpunk.Entity;
	import net.flashpunk.FP;
	import net.flashpunk.utils.Input;
	import net.flashpunk.utils.Key;

	
	/**
	 * ...
	 * @author Donatello
	 */
	public class Player extends Entity
	{
		private var power:Number=0.2;
		public var jumpPower:Number=10.0;
		public var hFriction:Number=0.95;
		public var vFriction:Number=0.99;
		public var xSpeed:Number=0;
		private var ySpeed:Number=0;
		private var gravity:Number = 0.3; 
		public var flipped:Boolean = false;
				
		public var state:String;
		
		public function Player(px:Number=305,py:Number=500) {
			
			x = px;
			y = py;
			
		
			
		}
		
		override public function update():void {
			var pressed:Boolean=false;
			
			if (state != "power")
			{
				if ((Input.check(Key.LEFT)) || (Input.check(Key.RIGHT))) {
					
					if(Input.check(Key.LEFT))
					{
						flipped = true;
						xSpeed-=power;
						pressed = true;
					}
					else
					{	
						flipped = false;
						xSpeed+=power;
						pressed = true;
					}
					
					if(state!="jump")
							state = "walking";
				}
				else if(state!="jump")state = "idle";
				
				if (collide("Wall",x,y +jumpPower)) {
					ySpeed = 0;
					if(state=="jump")
						state = "idle";
					if (Input.check(Key.UP)) {
						ySpeed -= jumpPower;
						state = "jump";
					}
				} else {
					ySpeed+=gravity;
				}
				
				
				if (Input.check(Key.SPACE))
				{
					if (state == "idle")
					{
						state = "power";
					}
					
				}	
			}
			
			if (Math.abs(xSpeed)<1&&! pressed) {
				xSpeed=0;
			}
			xSpeed*=hFriction;
			ySpeed*=vFriction;
			adjustXPosition();
			adjustYPosition();
		}
		private function adjustXPosition():void {
			for (var i:int = 0; i < Math.abs(xSpeed); i++) {
				
				if( (!collide("Wall",x+FP.sign(xSpeed),y))  &&  (!collide("WallBeakable",x+FP.sign(xSpeed),y)) ) {
					x+=FP.sign(xSpeed);
				} else {
					xSpeed=0;
					break;
				}
			}
		}
		private function adjustYPosition():void {
			for (var i:int=0; i<Math.abs(ySpeed); i++) {
				if (! collide("Wall",x,y+FP.sign(ySpeed))) {
					y+=FP.sign(ySpeed);
				} else {
					ySpeed=0;
					break;
				}
			}
		}
		
		public function actualizar():void {}
	}
}